package com.hzw.interceptor;

import com.hzw.utils.ObjectUtils;
import com.hzw.utils.TokenUtils;
import com.nimbusds.jose.JOSEException;
import net.minidev.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import static com.hzw.api.Api.CLIENT_ERROR;
import static com.hzw.api.Api.SERVER_ERROR;

/**
 * Created by Administrator on 2019/3/3.
 * 登录拦截器：在客户端浏览器调用接口之前，先拦截请求，验证用户是否登录，若已登录则继续请求，
 * 若没登录则停止请求，提示登录
 */
public class LoginInterceptor implements HandlerInterceptor{

    /**
     * 拦截请求，验证用户登录状态
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");     //设置字符编码，返回json信息给客户端
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter() ;

//        Cookie[] cookies = request.getCookies();    //获取cookie
        String token = request.getParameter("token");
        String userId = request.getParameter("userId");
//        if(!ObjectUtils.isNullOrEmpty(cookies)){    //从cookie中取出token
//            for (Cookie cookie : cookies) {
//                if(cookie.getName().equals("token")){
//                    token = cookie.getValue();
//                }else if(cookie.getName().equals("userId")){
//                    userId = cookie.getValue();
//                }
//            }
//        }

        Map<String, Object> result = new HashMap<>();   //返回结果

        //解析token
        try {
            if (!ObjectUtils.isNullOrEmpty(token)) {
                Map<String, Object> validMap = TokenUtils.valid(token); //获取解析token后的键值对map
                int i = (int) validMap.get("Result");
                if (i == 0) {                           //Result=0表示解析成功
                    System.out.println("token解析成功");
                    JSONObject jsonObject = (JSONObject) validMap.get("data");  //获取载荷的信息
                    System.out.println("userId是" + jsonObject.get("userId"));
                    System.out.println("token创建时间是"+jsonObject.get("sta"));
                    System.out.println("token过期时间是"+jsonObject.get("exp"));
                    if(jsonObject.get("userId").equals(userId)){    //利用token解析出来的userId和用户userId比较
                        response.reset();   //此处需要重置response，否则controller返回json会报错：已为此响应调用GetWriter（）
                        return true;                            //验证成功，请求放行，进入controller
                    }else{
                        result.put("code",CLIENT_ERROR);
                        result.put("msg","token错误，请重新登录！");
                        out.write(JSONObject.toJSONString(result));
                        out.flush();
                        out.close();
                        return false;
                    }
                }else if (i == 2) {    //Result=2表示token已过期
                    result.put("code",CLIENT_ERROR);
                    result.put("msg","token已过期，请重新登录！");
                    out.write(JSONObject.toJSONString(result));
                    out.flush();
                    out.close();
                    return false;
                }
            }else{
                result.put("code",CLIENT_ERROR);
                result.put("msg","token不能为空，请重新登录！");
                out.write(JSONObject.toJSONString(result));
                out.flush();
                out.close();
                return false;
            }
        } catch (ParseException e) {
            result.put("code",SERVER_ERROR);
            result.put("msg","token解析错误" + e.getMessage());
            out.write(JSONObject.toJSONString(result));
            out.flush();
            out.close();
            return false;
        } catch (JOSEException e) {
            result.put("code",SERVER_ERROR);
            result.put("msg",e.getMessage());
            out.write(JSONObject.toJSONString(result));
            out.flush();
            out.close();
            return false;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
